import requests


class ProxyHelper():

    def __init__(self):
        self.kdl_url = "https://dps.kdlapi.com/api/getdps/?secret_id=olrejp12b94qknshw4be&signature=m1y23gc6dg9ivkljppeovaaprqkqdgdh&num=1&pt=1&sep=1"
        self.proxies = self.get_ip()

    def get_ip(self):
        # 快代理后台生成的api链接   5s访问一次
        response = requests.get(self.kdl_url)
        proxy_ip = requests.get(self.kdl_url).text
        print("获取新IP地址：", proxy_ip)
        # 订单生成的账户与密码
        username = "d2356162166"
        password = "l7zee1jn"
        # 代理
        proxies = {
            "http": f"http://{username}:{password}@{proxy_ip}",
            "https": f"http://{username}:{password}@{proxy_ip}",
        }
        return proxies

    def requests_with_proxy(self, url, headers=None):
        for i in range(100):
            try:
                response = requests.get(url, headers=headers, proxies=self.proxies, allow_redirects=False)
            except requests.exceptions.ProxyError as e:
                print("ProxyError:", e)
                self.proxies = self.get_ip()
                continue
            except requests.exceptions.ReadTimeout as e:
                print("ReadTimeout:", e)
                self.proxies = self.get_ip()
                continue
            if response.status_code == 302:
                self.proxies = self.get_ip()
            elif response.status_code == 200:
                return response
        return None


"""
使用方法:
from proxy_helper import ProxyHelper
proxy_helper = ProxyHelper()
response = proxy_helper.requests_with_proxy(url, headers)
# response为requests的response对象
# 如果请求失败，会自动更换代理IP重试
# 如果重试100次后仍然失败，则返回None
# 如果请求成功，则返回requests的response对象
"""
